import React, { useEffect, useState } from 'react';
import cn from 'classnames';
// import Tabs from '@knownsec/react-component/dist/Tabs';
import Tabs, { TabPane } from '@kuiper-components/tabs';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import Button from '@knownsec/react-component/dist/Button';
import Input from '@knownsec/react-component/dist/Input';
import Select from '@knownsec/react-component/dist/Select';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import EmptyData from '../../../components/empty/EmptyData';
import s from './style.module.css';
import Label from '../../../components/Label';
import Helper from '../../../components/Helper';
import { filterNull, warnings } from '../../../../common/validation/common';
import fetch from 'API/fetch';
import locale from 'antd/es/locale/zh_CN.js';
import ConfirmBase from '../../../components/ConfirmBase';
import { LEVEL_NUM_LABEL_MAP } from '../../../../common/constants';
import { turnToUrlparam } from '../../../helpers/getUrlParams';
import { datetime } from '../../../../common/formatter';
import Message from '@knownsec/react-component/dist/Message';
import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../../../common/constants';
import { Link } from 'react-router-dom';
import CopyBoard from '../../../components/CopyBoard';

// const { TabPane } = Tabs
const levelColor = {
	5: '#D5342F',
	4: '#F04038',
	3: '#F18246',
	2: '#FCD94A',
};
const defaultFilter = {
	task_type: 'vul',
	level: '',
	target_url: '',
	target_name: '',
	risk_url: '',
	risk_name: '',
	reason: '',
	sort: '',
	page: 1,
	limit: 10,
};
const reasonMap = {
	1: '暂不关注',
	2: '误报',
	3: '其他',
};
export default function IgnoreRiskManage({
	history,
	location: { pathname, search },
}) {
	const prefilter = new URLSearchParams(search).get('filter');
	const filterS = prefilter ? JSON.parse(prefilter) || {} : {};
	const defaultFilter_ = { ...defaultFilter, ...filterS };
	const [filter, setFilter] = React.useState(defaultFilter_);
	const [tableData, setTableData] = useState({ data: [], total: 0 });
	const [selectedRows, setSelectedRows] = useState([]);
	const [loading, setLoading] = useState(false);
	const handleFilter = newFilter => {
		let f_ = JSON.parse(JSON.stringify(filter));
		if (newFilter === 'r') {
			f_ = defaultFilter;
		} else {
			f_ = {
				...f_,
				...newFilter,
			};
		}
		f_ = filterNull(f_);
		setFilter(f_);
		const params = encodeURI(JSON.stringify(f_));
		history.replace(pathname + '?filter=' + params);
		defaultFilter.task_type = f_.task_type;
		getIgnoreData(f_);
	};
	const getIgnoreData = (f_ = filter) => {
		setLoading(true);
		setSelectedRows([]);
		const params = turnToUrlparam(f_);
		fetch(`/api/v2/tasks/warning/ignore_list?${params}`, {
			method: 'GET',
		})
			.then(res => {
				if (res.code === 200) {
					setTableData({
						data: res?.data?.result?.map(item => {
							return {
								...item,
								key: item.warning_id,
								detail: {
									...item.detail,
									level: item.detail.level < 2 ? 2 : item.detail.level,
								},
							};
						}),
						total: res?.data?.count,
					});
				}
			})
			.finally(() => {
				setLoading(false);
			});
	};
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRows(newSelectedRowKeys);
	};
	const deleteIgnore = warning_ids => {
		ConfirmBase({
			className: 'w400',
			message: {
				icon: 'error',
				text: '恢复后，ScanV将对所选风险地址已恢复威胁进行监测下一任务生效。',
			},
			onConfirm: callback => {
				fetch(`/api/v2/tasks/warning/ignore`, {
					method: 'DELETE',
					body: JSON.stringify({ warning_ids }),
				})
					.then(res => {
						if (res.code === 200) {
							Message.show({ type: 'success', message: '操作成功' });
							getIgnoreData();
						}
					})
					.finally(() => {
						callback();
					});
			},
			oncancel: () => {
				setIgnoreReason('1');
			},
		});
	};
	const columns = [
		{
			dataIndex: 'target_name',
			title: '资产名称',
			key: 'target_name',
			render(e) {
				return <CopyBoard text={e} className={'db'} />;
			},
		},
		{
			dataIndex: 'target_url',
			title: '资产地址',
			key: 'target_url',
			render(e) {
				return <CopyBoard text={e} className={'db'} />;
			},
		},
		{
			dataIndex: ['detail', 'affects'],
			title: '风险地址',
			key: 'affects',
			render(e) {
				return <CopyBoard text={e} className={'db'} />;
			},
		},
		{
			dataIndex: ['detail', 'title'],
			title: filter?.task_type === 'vul' ? '漏洞名称' : '威胁名称',
			key: 'title',
			render(e) {
				return <CopyBoard text={e} className={'db'} />;
			},
		},
		['vul', 'ssl'].includes(filter?.task_type)
			? {
					dataIndex: ['detail', 'category'],
					title: filter?.task_type === 'ssl' ? '威胁类型' : '漏洞类型',
					key: 'category',
					render(e) {
						return filter?.task_type === 'ssl'
							? WARNING_CATEGORY_KEY_LABEL_MAP.ssl[e]
							: e;
					},
			  }
			: '',
		{
			dataIndex: ['detail', 'level'],
			title: '威胁等级',
			key: 'level',
			render(e) {
				return (
					<span style={{ color: levelColor[e] }}>{LEVEL_NUM_LABEL_MAP[e]}</span>
				);
			},
		},
		{
			dataIndex: ['reason', 'type'],
			title: '忽略原因',
			key: 'type',
			render(e) {
				return reasonMap[e];
			},
		},
		{
			dataIndex: 'ignoredTime',
			title: '忽略时间',
			showSorterTooltip: false,
			width: 180,
			sortOrder: filter?.sort
				? filter?.sort === 'ignoredTime'
					? 'ascend'
					: filter?.sort === '-ignoredTime'
					? 'descend'
					: null
				: null,
			sorter: (a, b) => {},
			key: 'ignoredTime',
			render(e, { ignored_time }) {
				return datetime(ignored_time);
			},
		},
		{
			dataIndex: 'method',
			title: '操作',
			key: 'method',
			width: 140,
			render(e, row) {
				return (
					<>
						<Link
							className={'main-color mr5'}
							to={{
								pathname: `/policy-manage/ignore-risk-detail/`,
								search: `task_type=${filter?.task_type}`,
								state: {
									warning_id: row.warning_id,
									category: row.detail.category || '',
								},
								sendState: {
									warning_id: row.warning_id,
									title: row.detail.title,
									url: row.detail.affects,
								},
							}}
						>
							查看详情
						</Link>
						<Button
							type="text"
							className="p0"
							onClick={() => deleteIgnore([row.warning_id])}
						>
							恢复
						</Button>
					</>
				);
			},
		},
	].filter(i => i);
	useEffect(() => {
		getIgnoreData();
	}, []);
	return (
		<div className={s.ignoreRiskManage}>
			<div className={s.header}>
				<Breadcrumb className={s.breadcrumb}>
					<Item disabled key="policy-manage">
						综合管理
					</Item>
					<Item active>已忽略威胁</Item>
				</Breadcrumb>
			</div>
			<div className={cn('scanv-page-container', s.container)}>
				<Label className={'ml24 df aic'}>
					已忽略威胁
					<Helper
						placement="top"
						overlay="ScanV将不再监测以下风险地址的威胁。"
					/>
				</Label>
				<Tabs
					className={cn(s.tabs)}
					activeKey={filter?.task_type}
					onChange={task_type => handleFilter({ ...filter, task_type })}
				>
					<TabPane key="vul" tab={<span className="fs14">Web漏洞</span>}>
						<></>
					</TabPane>
					<TabPane key="ssl" tab={<span className="fs14">SSL安全</span>}>
						<></>
					</TabPane>
					<TabPane
						key="securityEvent"
						tab={<span className="fs14">安全事件</span>}
					>
						<></>
					</TabPane>
					<TabPane key="content" tab={<span className="fs14">内容违规</span>}>
						<></>
					</TabPane>
					<TabPane key="changeCheck" tab={<span className="fs14">篡改</span>}>
						<></>
					</TabPane>
					<TabPane key="host" tab={<span className="fs14">主机监测</span>}>
						<></>
					</TabPane>
				</Tabs>
				<div className="df aic jcsb mb10 pl24 pr24 pb10 mt20">
					<div className="df aic">
						<Input
							onChange={({ value: target_name }) =>
								setFilter({ ...filter, target_name })
							}
							onSearch={({ value: target_name }) =>
								handleFilter({ target_name, page: 1 })
							}
							search
							value={filter?.target_name}
							placeholder="搜索资产名称"
							className={'w160 mr10'}
						/>
						<Input
							onChange={({ value: target_url }) =>
								setFilter({ ...filter, target_url })
							}
							onSearch={({ value: target_url }) =>
								handleFilter({ target_url, page: 1 })
							}
							search
							value={filter?.target_url}
							placeholder="搜索资产地址"
							className={'w160 mr10'}
						/>
						<Input
							onChange={({ value: risk_url }) =>
								setFilter({ ...filter, risk_url })
							}
							onSearch={({ value: risk_url }) =>
								handleFilter({ risk_url, page: 1 })
							}
							search
							value={filter?.risk_url}
							placeholder="搜索风险地址"
							className={'w160 mr10'}
						/>
						<Input
							onChange={({ value: risk_name }) =>
								setFilter({ ...filter, risk_name })
							}
							onSearch={({ value: risk_name }) =>
								handleFilter({ risk_name, page: 1 })
							}
							search
							value={filter?.risk_name}
							placeholder="搜索威胁名称"
							className={'w160 mr10'}
						/>
					</div>
					<div className="df aic">
						<Select
							className={'w160 mr10'}
							value={[filter?.level]}
							placeholder="威胁等级"
							option={Object.entries(LEVEL_NUM_LABEL_MAP)
								?.sort((a, b) => b[0] - a[0])
								?.map(([value, label]) => {
									return { label, value };
								})}
							onChange={({ selectedItem }) =>
								handleFilter({ ...filter, level: selectedItem[0]?.value || '' })
							}
							clearable
						/>
						<Select
							className={'w160 mr10'}
							value={[filter?.reason]}
							placeholder="忽略原因"
							option={Object.entries(reasonMap)?.map(([value, label]) => {
								return { label, value };
							})}
							onChange={({ selectedItem }) =>
								handleFilter({
									...filter,
									reason: selectedItem[0]?.value || '',
								})
							}
							clearable
						/>
						<Button className={'primary-btn'} onClick={() => handleFilter('r')}>
							重置
						</Button>
					</div>
				</div>
				<div className="pl24 pr24 small-table">
					<Table
						pro
						columns={columns}
						loading={loading}
						data={tableData?.data}
						locale={locale.Table}
						key={Date.now()}
						empty={<EmptyData borderless className={s.h208} />}
						rowSelection={{
							selectedRowKeys: selectedRows,
							width: 50,
							onChange: onSelectChange,
						}}
						onChange={(pagination, filters, sorter) => {
							if (filters || sorter.order) {
								const field = sorter.field;
								const filterMap = Object.keys(filters).reduce((t, i) => {
									if (filters[i]) {
										if (filters[i].length > 0) t[i] = filters[i]?.join(',');
									} else {
										t[i] = '';
									}
									return t;
								}, {});
								const newF = {
									...filter,
									page: 1,
									...filterMap,
									sort:
										sorter.order === 'descend'
											? '-' + field
											: sorter.order === 'ascend'
											? field
											: '',
								};
								if (
									JSON.stringify(filterNull(newF)) ===
									JSON.stringify(filterNull(filter))
								) {
									return false;
								} else {
									handleFilter(newF);
								}
							}
						}}
					/>
					<div className="mt10 df aic jcsb">
						<div>
							{selectedRows.length > 0 && (
								<div className="warning-color fs12">
									当前已选择{' '}
									<span className="main-color">
										{selectedRows?.length || 0}
									</span>{' '}
									个威胁
								</div>
							)}
							<Button
								type="text"
								className="p0"
								disabled={selectedRows?.length === 0}
								onClick={() => deleteIgnore(selectedRows)}
							>
								批量恢复
							</Button>
						</div>
						{tableData?.total > 0 && (
							<Pagination
								showTotal={total => `共${total}条`}
								total={tableData?.total}
								className={s.pagination}
								showSizeChanger={true}
								pageSizeOptions={['10', '20', '50']}
								current={filter?.page}
								pageSize={filter?.limit}
								page={filter?.page}
								onChange={(page, limit) => {
									handleFilter({ ...filter, page, limit });
								}}
							/>
						)}
					</div>
				</div>
			</div>
		</div>
	);
}
